package com.zhongan.boot.listener;

import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener;

/**
 * spring boot启动异常时执行事件
 * 在异常发生时，最好是添加虚拟机对应的钩子进行资源的回收与释放，能友善的处理异常信息。
 * 
 * @author chengkai
 *
 */
public class MyApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> {

	private Thread shutdownHook;

	@Override
	public void onApplicationEvent(ApplicationFailedEvent event) {
		System.out.println("spring boot 启动异常监听");
		Throwable throwable = event.getException();
		handleThrowable(throwable);
	}

	/*处理异常*/
	private void handleThrowable(Throwable throwable) {
	}

	public void registerShutdownHook() {
		if (this.shutdownHook == null) {
			// No shutdown hook registered yet.
			this.shutdownHook = new Thread() {
				@Override
				public void run() {
					// 释放各种资源
					// doClose();
				}
			};
			Runtime.getRuntime().addShutdownHook(this.shutdownHook);
		}
	}

}